﻿using System;
using System.Web;
using FikriKibar.Common.Entities;
using FikriKibar.Common.Helpers;
using FikriKibar.UI.WebCommon.Abstract;

namespace FikriKibar.UI.WebCommon.Security
{
    public class WebSecurityManager : IWebSecurityManager
    {
        public void Set(FikriKibarIdentity identity, DateTime expirationDateTime, string cookieName, bool rememberMe)
        {
            var serializedIdentity = SerializationHelper.SerializeToString(identity);
            var encryptedSerializedIdentity = SecurityHelper.Encrypt(serializedIdentity);
            HttpContext.Current.Response.Cookies.Add(new HttpCookie(cookieName, encryptedSerializedIdentity)
            {
                Expires = expirationDateTime
            });
        }

        public FikriKibarPrincipal Get(string cookieName)
        {
            var identityCookie = HttpContext.Current.Request.Cookies[cookieName];
            var identityCookieValue = identityCookie?.Value;
            if (string.IsNullOrEmpty(identityCookieValue)) return null;
            var decryptedIdentityCookieValue = SecurityHelper.Decrypt(identityCookieValue);
            var identity = SerializationHelper.DeserializeFromString<FikriKibarIdentity>(decryptedIdentityCookieValue);
            var principle = new FikriKibarPrincipal(identity);
            return principle;
        }

        public void Remove(string cookieName)
        {
            var currentCookie = HttpContext.Current.Request.Cookies[cookieName];
            HttpContext.Current.Response.Cookies.Remove(cookieName);
            if (currentCookie == null) return;
            currentCookie.Expires = DateTime.Now.AddDays(-10);
            currentCookie.Value = null;
            HttpContext.Current.Response.SetCookie(currentCookie);
        }
    }
}
